/*
 * @Author: 曹捷
 * @Date: 2020-04-22 17:02:31
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-01-07 10:35:19
 * @Description: 系统工具类
 */
const util = {}

util.util = {
    /*克隆一个对象*/
    cloneObj (obj) {
        var newObj = {};
        let type = Object.prototype.toString.call(obj)
        if (type.indexOf('Array') !== -1) {
            newObj = [];
        }
        for (var key in obj) {
            var val = obj[key];
            newObj[key] = (val !== null && typeof val === 'object') ? util.util.cloneObj(val) : val;
        }
        return newObj;
    },
    cleanObj (obj) {
        for (var key in obj) {
            if (obj[key] instanceof Array) {
                obj[key] = [];
            } else if (obj[key] instanceof Number) {
                obj[key] = 0;
            } else {
                obj[key] = '';
            }

        }
    },
    /**
     * 数组删除指定的内容
     */
    removeByValue: function (arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
        return arr;
    },
    getArrayIndexByOptions: function (arry, value, optionList) {
        for (var i = 0; i < arry.length; i++) {
            var res = true;
            for (var it in optionList) {
                if (arry[i][optionList[it]] != value[optionList[it]]) {
                    res = false;
                }
            }
            if (res) {
                return i;
            }
        }
        return -1;
    },
    getArrayObjectByValues: function (arry, value, option) {
        var arr = arguments;
        for (let i = 0; i < arry.length; i++) {
            if (arr.length > 3) {
                var find = true;
                for (var index = 2; index < arr.length; index++) {
                    if (arry[i][arr[index]] != value[arr[index]]) {
                        find = false;
                    }
                }
                if (find) return arry[i];
            } else {
                if (arry[i][option] == value[option]) {
                    return arry[i];
                }
            }

        }
        return null;
    },
    /**
     * 保留原对象基础属性，集成新对象里面的所有的属性值，属性值相同的替换成新属性
     * source {a:1,b:1,c:1}  newdata{b:1,c:1,d:1}  = {a:1,b:2,c:2,d:1}
     * @param {*} source 
     * 原数据对象
     * @param {*} newdata 
     * 要赋值给原数据对象的内容
     */
    extendObj (source, newdata) {
        if (source == null) return;
        for (var property in newdata) {
            console.log('extendObj -> typeof newdata[property]', Object.prototype.toString.call(newdata[property]))

            if (typeof newdata[property] === "object") {
                console.log('extendObj -> newdata[property]', newdata[property])
                if (source[property] == null) {
                    if (newdata[property] instanceof Array) {
                        source[property] = [];
                    } else {
                        source[property] = {};
                    }
                }
                this.extendObj(source[property], newdata[property]);
            } else {
                source[property] = newdata[property];
            }

        }
        return source;
    },
    /**
     * 保留原对象基础属性，新对象里面对应的属性值有值的情况下进行更新
     * source {a:1,b:1,c:1}  newdata{b:1,c:1,d:1}  = {a:1,b:2,c:2}
     * @param {*} source 
     * 原数据对象
     * @param {*} newdata 
     * 要赋值给原数据对象的内容
     */
    assignObj (source, newdata) {
        if (source == null) return;
        for (var property in source) {
            if (typeof source[property] === "object" && typeof newdata[property] === "object") {
                this.assignObj(source[property], newdata[property]);
            } else if (newdata[property] !== null && newdata[property] !== '' && newdata[property] !== undefined) {
                source[property] = newdata[property];
            }
        }
        return source;
    },
    /*在传递数据的时候对对象进行中文编码处理*/
    encodeParemt (paremt) {
        var a = {};
        for (var i in paremt) {
            a[i] = encodeURI(paremt[i]);
        }
        return a;
    },
    /**
     * 获取url后面的参数  返回json
     */
    getParams: function () {
        var url = window.location.hash;
        var theRequest = null;
        if (url.indexOf("?") != -1) {
            url = url.split("?")[1];
            theRequest = new Object();
            var str = url.substr(0);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
        if (theRequest != null)
            return theRequest;
        else
            return null;
    },
    //数组去重
    ArrayUnique: function (arr) {
        var res = [];
        var json = {};
        for (var i = 0; i < arr.length; i++) {
            if (!json[arr[i]]) {
                res.push(arr[i]);
                json[arr[i]] = 1;
            }
        }
        return res;
    },
    parseParam (queryConfig, baseUrl) { //吧对象转为url字符拼接
        var _str = "";
        for (var o in queryConfig) {
            if (queryConfig[o] != -1) {
                _str += o + "=" + queryConfig[o] + "&";
            }
        }
        var _str = _str.substring(0, _str.length - 1);
        if (baseUrl) {
            let icon = baseUrl.indexOf('?') !== -1 ? '' : '?'
            return `${baseUrl}${icon}${_str}`
        }
        return _str;
    },
    /**
     * 节流函数
     * 
     * @param {*} func 
     * @param {*} delay 
     * 时间毫秒
     * 在设定的时间内 只执行一次
     * 
     * 额外增加，最后一次时间内 函数执行
     */
    throttle (func, delay) {
        var prev = Date.now();
        var timer = null;
        return function () {
            var context = this;
            var args = arguments;
            var now = Date.now();
            if (now - prev >= delay) {
                // console.log(33, now - prev)
                func.apply(context, args);
                prev = Date.now();
            } else {
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    // console.log(22, now - prev)
                    func.apply(context, args);
                }, delay);
            }
        }
    },
    /**
     * 防抖
     * @param {*} func 
     * @param {*} wait 
     * 一定时间内 只执行最后一次
     */
    debounce (func, wait) {
        let timeout;
        return function () {
            let context = this;
            let args = arguments;
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args)
            }, wait);
        }
    },
    // throttle (fn, wait) {
    //     var pre = Date.now();
    //     return function () {
    //         var context = this;
    //         var args = arguments;
    //         var now = Date.now();
    //         if (now - pre >= wait) {
    //             fn.apply(context, args);
    //             pre = Date.now();
    //         }
    //     }
    // },
    urlEncode (param, key, encode) {
        if (param == null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += key + '=' + param;
        } else {
            for (var i in param) {
                if (paramStr === '') {
                    paramStr += '?'
                } else {
                    paramStr += '&'
                }
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
                paramStr += urlEncode(param[i], k, encode)
            }
        }
        return paramStr;
    },
    //字符串转base64
    encode (str) {
        // 对字符串进行编码
        var encode = encodeURI(str);
        // 对编码的字符串转化base64
        var base64 = btoa(encode);
        return base64;
    },
    // base64转字符串
    decode (base64) {
        // 对base64转编码
        var decode = atob(base64);
        // 编码转字符串
        var str = decodeURI(decode);
        return str;
    },
    // 是否是空值  true   空值 空对象  
    isNull (item) {
        if (item) {
            if (Object.prototype.toString.call(item).indexOf('Array') !== -1) {
                return item.length === 0
            }
            return false
        }
        return true
    }
}
util.array = {
    findAllIndex (list, func) {
        let arr = []
        for (let i = 0; i < list.length; i++) {
            if (func(list[i])) {
                arr.push(i)
            }
        }
        return arr
    },
    treeToArray (nodes, childrenName) {
        var r = [];
        if (Array.isArray(nodes)) {
            for (var i = 0, l = nodes.length; i < l; i++) {
                r.push(nodes[i]); // 取每项数据放入一个新数组
                if (Array.isArray(nodes[i][childrenName]) && nodes[i][childrenName].length > 0)
                    // 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
                    r = r.concat(util.array.treeToArray(nodes[i][childrenName], childrenName));
                delete nodes[i][childrenName]
            }
        }
        return r;
    },
    /**
     * 删除数组的某个值
     * @param {*} arr 
     * 需要删除的源数组
     * @param {*} key 
     * 对比的key
     * @param {*} value 
     * 对比的值
     */
    removeItem (arr, key, value) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i][key] == value) {
                arr.splice(i, 1)
                return
            }
        }
    }
}
export default util;
